package ru.sgu.acm.database;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import ru.sgu.acm.misc.Constants;

import javax.sql.DataSource;

/**
 * Author: Vitaly Goldshteyn
 */
public class DataSourceFactory {
    private static DataSource dataSource = null;

    /**
     * Singletone connection to database.
     * @return DataSource to database
     */
    public static DataSource getDataSource() {
        if (dataSource == null) {
            dataSource = newDataSource();
        }
        return dataSource;
    }

    private static DataSource newDataSource() {
        MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
        dataSource.setUser(Constants.getDatabaseUser());
        dataSource.setPassword(Constants.getDatabasePassword());
        dataSource.setUrl(Constants.getDatabaseUrl());
        return dataSource;
    }

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Can not load mysql driver.", e);
        }
    }
}
